/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.killHanlder;

import cn.ac.iie.di.datadock.rdata.exchange.client.exception.REConnectionException;
import cn.ac.iie.di.datadock.rdata.exchange.client.v1.session.RESendSession;
import cn.ac.iie.di.wx.common.RuntimeEnv;
import cn.ac.iie.di.wx.vo.PicUrlVo;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.logging.Level;
import org.apache.log4j.Logger;
import sun.misc.Signal;
import sun.misc.SignalHandler;

/**
 *
 * @author Administrator
 */
public class KillHandler implements SignalHandler {

    public static Logger logger = org.apache.log4j.Logger.getLogger(KillHandler.class.getName());
    RESendSession session;
    LinkedBlockingQueue<PicUrlVo> picUrlBlockingQueue;

    @Override
    public void handle(Signal signal) {
        //写入文件
        if (signal.getName().equals("TERM")) {
            while (true) {
                if (picUrlBlockingQueue.size() == 0) {
                    try {
                        Thread.sleep(1000);
                        int sessionSize = session.getCurrentDataSize();//当前缓存的数据总量
                        int sessionPac = session.getCurrentPacNum();//查看当前缓存的数据包数
                        if (picUrlBlockingQueue.size() == 0 && sessionSize == 0 && sessionPac == 0) {
                            try {
                                session.closeGracefully();
                            } catch (REConnectionException ex) {
                                logger.error(ex.getMessage(), ex);
                            }
                            break;
                        }
                    } catch (InterruptedException ex) {
                        logger.error(ex.getMessage(), ex);
                    }
                }
            }
        }
    }

    public void registerSignal(String signalName) {
        Signal signal = new Signal(signalName);
        Signal.handle(signal, this);
    }

    public RESendSession getSession() {
        return session;
    }

    public void setSession(RESendSession session) {
        this.session = session;
    }

    public LinkedBlockingQueue<PicUrlVo> getPicUrlBlockingQueue() {
        return picUrlBlockingQueue;
    }

    public void setPicUrlBlockingQueue(LinkedBlockingQueue<PicUrlVo> picUrlBlockingQueue) {
        this.picUrlBlockingQueue = picUrlBlockingQueue;
    }
}
